package com.gs.SynPatrolRep.activity.event;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gs.SynPatrolRep.R;
import com.gs.SynPatrolRep.activity.ImagePreviewActivity;
import com.gs.SynPatrolRep.activity.base.BaseActivity;
import com.gs.SynPatrolRep.adapter.PatrolItemPhotoAdapter;
import com.gs.SynPatrolRep.adapter.ReportResultPhotoAdapter;
import com.gs.SynPatrolRep.adapter.base.BaseAdapter;
import com.gs.SynPatrolRep.apiresult.ApiResultData;
import com.gs.SynPatrolRep.constant.AllConstants;
import com.gs.SynPatrolRep.control.ItemText;
import com.gs.SynPatrolRep.control.ShowItem;
import com.gs.SynPatrolRep.db.dto.CreatePalBillItemDto;
import com.gs.SynPatrolRep.db.dto.PalBillEventDto;
import com.gs.SynPatrolRep.db.dto.ShortDto;
import com.gs.SynPatrolRep.dialog.ComboPicDialog;
import com.gs.SynPatrolRep.dialog.LoadingDialogUtils;
import com.gs.SynPatrolRep.dialog.ShortDialog;
import com.gs.SynPatrolRep.dialog.ToastDialogUtils;
import com.gs.SynPatrolRep.presenter.CreateReportPresenter;
import com.gs.SynPatrolRep.util.DateUtil;
import com.gs.SynPatrolRep.util.FileUtils;
import com.gs.SynPatrolRep.util.ImageUtil;
import com.gs.SynPatrolRep.util.OKHttpUtil;
import com.gs.SynPatrolRep.util.PhotoUtil;
import com.gs.SynPatrolRep.util.SPUtil;
import com.gs.SynPatrolRep.view.ICreateReportView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class CreateReportActivity extends BaseActivity<ICreateReportView, CreateReportPresenter>
        implements ICreateReportView {

    private ArrayList<CreatePalBillItemDto.ExctPhoto> listPhoto;
    private List<PalBillEventDto.PalBillEventPhotoDto> photos;
    private ArrayList<String> listPhotos;
    private PatrolItemPhotoAdapter adapterPhoto;
    private ReportResultPhotoAdapter adapter;
    private ShowItem itemImportance, itemReporter, itemTime, itemLocation, itemState, itemHandle, itemHandleTime;
    private ItemText itemNum;
    private TextView tvResult, tvTitle;
    private List<ShortDto> list;
    private String position;
    private EditText etCon;
    private String time, siteId, id;
    private int type;

    @Override
    public int getLayoutId() {
        return R.layout.activity_create_report;
    }

    @Override
    public void initView() {
        type = getIntent().getIntExtra(AllConstants.INFO_TYPE, 0);
        OnClickListener onClickListener = new OnClickListener();
//        單號
        itemNum = findViewById(R.id.item_num);
//        事件内容
        etCon = findViewById(R.id.et_con);
//        發生位置
        itemLocation = findViewById(R.id.item_location);
//        重要性
        itemImportance = findViewById(R.id.item_importance);
        itemImportance.setOnClickListener(onClickListener);
//        報告人
        itemReporter = findViewById(R.id.item_reporter);
        itemReporter.setText(SPUtil.getInstance().getString(AllConstants.USER));
//        報告時間
        itemTime = findViewById(R.id.item_time);
//        照片
        tvTitle = fd(R.id.tv_photo_title);
        RecyclerView rvPhoto = findViewById(R.id.rv_pic);
        rvPhoto.setLayoutManager(new GridLayoutManager(this, 3));
//        保存
        findViewById(R.id.btn_save).setOnClickListener(onClickListener);
//        返回
        findViewById(R.id.btn_return).setOnClickListener(onClickListener);
        if (type == 3) {
            toolBarTitle.setTitle(getString(R.string.view_create_report));
            // 状态
            itemState = fd(R.id.item_state);
            // 处理人
            itemHandle = fd(R.id.item_handle);
            // 处理时间
            itemHandleTime = fd(R.id.item_handle_time);
            // 处理结果
            tvResult = fd(R.id.tv_result);
            tvTitle.setText(R.string.photo1);
            fd(R.id.ll_btn).setVisibility(View.GONE);
            id = getIntent().getStringExtra(AllConstants.ID);
            etCon.setEnabled(false);
            photos = new ArrayList<>();
            adapter = new ReportResultPhotoAdapter(this, photos, R.layout.rvitem_photo);
            adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClickListener(View v, int position) {
                    Intent intent = new Intent();
                    intent.setClass(CreateReportActivity.this, ImagePreviewActivity.class);
                    if (listPhotos == null) {
                        listPhotos = new ArrayList<>();
                        for (int i = 0; i < photos.size(); i++) {
                            listPhotos.add(OKHttpUtil.IMG_URL + photos.get(i).getPhoto());
                        }
                    }
                    intent.putExtra(AllConstants.WHAT, listPhotos);
                    intent.putExtra(AllConstants.ID, position);
                    startActivity(intent);
                }
            });
            rvPhoto.setAdapter(adapter);
            mPresenter.getData(id);
        } else {
            toolBarTitle.setTitle(getString(R.string.create_report));
            Drawable drawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_photo, null);
            drawable.setBounds(0,0,drawable.getIntrinsicWidth(),drawable.getIntrinsicHeight());
            tvTitle.setText(R.string.eventPhoto);
            tvTitle.setCompoundDrawables(null, null, drawable, null);
            time = DateUtil.getInstance().DateTimeToStr(new Date(), "yyyy-MM-dd hh:mm:ss");
            itemTime.setText(time);
            fd(R.id.ll_show).setVisibility(View.GONE);
            listPhoto = new ArrayList<>();
            adapterPhoto = new PatrolItemPhotoAdapter(this, this, listPhoto, 3);
            adapterPhoto.setOnItemClickListener(new PatrolItemPhotoAdapter.OnItemClickListener() {
                @Override
                public void onItemClickListener(View v, int position) {
                    Intent intent = new Intent();
                    intent.setClass(CreateReportActivity.this, ImagePreviewActivity.class);
                    ArrayList<String> listPhotos = new ArrayList<>();
                    for (int i = 0; i < listPhoto.size(); i++) {
                        listPhotos.add(listPhoto.get(i).getPhoto());
                    }
                    intent.putExtra(AllConstants.WHAT, listPhotos);
                    intent.putExtra(AllConstants.ID, position);
                    startActivity(intent);
                }
            });
            rvPhoto.setAdapter(adapterPhoto);
            if (type == 0) {
                itemNum.setVisibility(View.GONE);
                itemLocation.setOnClickListener(onClickListener);
                etCon.setHint(R.string.p_input_content);
                itemImportance.setHint(R.string.p_sel_level);
                itemLocation.setHint(R.string.p_sel_location);
            } else {
                etCon.setEnabled(false);
                String num = SPUtil.getInstance().getString(AllConstants.NUM);
                itemNum.setText(num == null ? "" : num);
                Bundle bundle = getIntent().getBundleExtra(AllConstants.WHAT);
                if (bundle != null) {
                    itemLocation.setText(bundle.getString(AllConstants.PLAN) == null ?
                            "" : bundle.getString(AllConstants.PLAN));
                    etCon.setText(bundle.getString(AllConstants.DESCRIBE) == null ?
                            "" : bundle.getString(AllConstants.DESCRIBE));
                }
            }
        }
    }

    @Override
    public CreateReportPresenter createPresenter() {
        return new CreateReportPresenter();
    }

    @Override
    public void per() {

    }

    @Override
    public String getSiteId() {
        return siteId;
    }

    @Override
    public String getName() {
        return etCon.getText().toString();
    }

    @Override
    public Integer getLevelType() {
        return Integer.parseInt(position);
    }

    @Override
    public String getRepAt() {
        return time;
    }

    @Override
    public String getReperId() {
        return SPUtil.getInstance().getString(AllConstants.ID);
    }

    @Override
    public List<CreatePalBillItemDto.ExctPhoto> getPhotos() {
        for (int i = 0; i < listPhoto.size(); i++) {
            String photo = listPhoto.get(i).getPhoto();
            if (photo.startsWith(OKHttpUtil.IMG_URL)) {
                listPhoto.get(i).setPhoto(photo.substring(OKHttpUtil.IMG_URL.length()));
            }
        }
        return listPhoto;
    }

    @Override
    public void onGetDataSuccess(ApiResultData<PalBillEventDto> apiResult) {
        if (apiResult.getStatus() != 2000) {
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResult.getMessage());
            return;
        }
        PalBillEventDto data = apiResult.getData();
        if (data != null) {
            itemNum.setText(data.getEventNum() == null ? "" : data.getEventNum());
            etCon.setText(data.getName() == null ? "" : data.getName());
            itemImportance.setText(data.getLevelTypeName() == null ? "" : data.getLevelTypeName());
            itemTime.setText(data.getRepAt() == null ? "" : data.getRepAt());
            itemState.setText(data.getProName() == null ? "" : data.getProName());
            itemHandleTime.setText(data.getProAt() == null ? "" : data.getProAt());
            tvResult.setText(data.getProResult() == null ? "" : data.getProResult());
            if (data.getSite() != null) {
                itemLocation.setText(data.getSite().getName());
            }
            if (data.getReper() != null) {
                itemReporter.setText(data.getReper().getName());
            }
            if (data.getProer() != null) {
                itemHandle.setText(data.getProer().getName());
            }
            if (data.getPhotos() != null && !data.getPhotos().isEmpty()) {
                photos.addAll(data.getPhotos());
                adapter.notifyDataSetChanged();
            }else {
                fd(R.id.ll_photo).setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onGetDataFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public void onUploadImgSuccess(ApiResultData<String> apiResultData, int position) {
        if (apiResultData.getStatus() != 2000) {
            adapterPhoto.delete(position);
            ToastDialogUtils.getInstance().showInfoMessage(this, apiResultData.getMessage());
            return;
        }
        listPhoto.set(position, new CreatePalBillItemDto.ExctPhoto(OKHttpUtil.IMG_URL + apiResultData.getData()));
    }

    @Override
    public void onUploadImgFails(Exception e, int position) {
        adapterPhoto.delete(position);
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public void onGetComboSuccess(ApiResultData<List<ShortDto>> apiResult) {
        if (apiResult.getStatus() != 2000) {
            Toast.makeText(this, apiResult.getMessage(), Toast.LENGTH_LONG).show();
            return;
        }
        new ShortDialog(this, apiResult.getData(), R.string.p_sel, siteId,
                new ShortDialog.IChoiceListener() {
                    @Override
                    public void getChoiceFromDialog(ShortDto bean) {
                        siteId = bean.getId();
                        itemLocation.setText(bean.getName());
                    }
                }).show();
    }

    @Override
    public void onGetComboFails(Exception msg) {
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public void onCreateSuccess(ApiResultData<String> apiResultData) {
        Toast.makeText(this, apiResultData.getMessage(), Toast.LENGTH_LONG).show();
        if (apiResultData.getStatus() == 2000) {
            setResult(1);
            finish();
        }
    }

    @Override
    public void onCreateFails(Exception e) {
        ToastDialogUtils.getInstance().showInfoMessage(this, getString(R.string.network_error));
    }

    @Override
    public void showLoading() {
        LoadingDialogUtils.getInstance().showLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialogUtils.getInstance().dismiss();
    }

    class OnClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.item_importance:
                    if (list == null || list.isEmpty()) {
                        list = new ArrayList<>();
                        list.add(new ShortDto("1", getResources().getString(R.string.high)));
                        list.add(new ShortDto("2", getResources().getString(R.string.middle)));
                        list.add(new ShortDto("3", getResources().getString(R.string.low)));
                    }
                    new ShortDialog(CreateReportActivity.this, list, R.string.p_sel, position, new ShortDialog.IChoiceListener() {
                        @Override
                        public void getChoiceFromDialog(ShortDto bean) {
                            position = bean.getId();
                            itemImportance.setText(bean.getName());
                        }
                    }).show();
                    break;
                case R.id.item_location:
                    mPresenter.combo("palSites");
                    break;
                case R.id.btn_save:
                    if (TextUtils.isEmpty(position)) {
                        ToastDialogUtils.getInstance().showInfoMessage(CreateReportActivity.this, "請選擇事件重要性");
                        return;
                    }
                    CreatePalBillItemDto.Event event = new CreatePalBillItemDto.Event();
                    event.setAreaId(SPUtil.getInstance().getString(AllConstants.AREA_ID));
                    event.setLevelType(getLevelType());
                    event.setName(getName());
                    event.setPhotos(getPhotos());
                    event.setRepAt(getRepAt());
                    event.setReperId(getReperId());
                    if (type == 0) {
                        if (TextUtils.isEmpty(getSiteId())) {
                            ToastDialogUtils.getInstance().showInfoMessage(CreateReportActivity.this, "請選擇發生位置");
                            return;
                        }
                        event.setSiteId(getSiteId());
                        try {
                            mPresenter.create(event);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        Intent intent = new Intent();
                        intent.putExtra(AllConstants.WHAT, event);
                        setResult(1, intent);
                        finish();
                    }
                    break;
                case R.id.btn_return:
                    finish();
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != 0) {
            if (requestCode == AllConstants.PIC_GALLERY) {
                if (data != null && data.getData() != null) {
                    String path = FileUtils.getFilePathByUri(this, data.getData());
                    uploadImg(path);
                }
            } else if (requestCode == AllConstants.PIC_CAMERA) {
                Bitmap bitmap = PhotoUtil.getInstance().rotatingPic(PhotoUtil.getInstance().getAngle(), BitmapFactory.decodeFile(PhotoUtil.getInstance().imgUrl));
                String path = ImageUtil.getInstance().bitmapToUrl(this, bitmap);
                uploadImg(path);
            }
        }
    }

    private void uploadImg(String path) {
        adapterPhoto.add(new CreatePalBillItemDto.ExctPhoto(path));
        try {
            mPresenter.uploadImg(path, listPhoto.size() - 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 申请相机权限后返回
            if (requestCode == ComboPicDialog.PIC_CAREMA) {
                PhotoUtil.getInstance().toCamera(this);
            }
            // 申请读取图库权限后返回
            else if (requestCode == ComboPicDialog.PIC_GALLERY) {
                PhotoUtil.getInstance().toGallery(this);
            }
        }
    }
}